﻿'
' Quiz Module for DotNetNuke
' Project Contributors - Will Strohl (http://www.WillStrohl.com)
'
'Copyright (c) 2011, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Quiz Module for DotNetNuke, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.UI.Skins.Controls
Imports DotNetNuke.Entities.Icons
Imports DotNetNuke.Entities.Icons.IconController
Imports DotNetNuke.Security
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.UI.Skins.Skin
Imports System.Text
Imports System.Web.UI
Imports WillStrohl.Modules.Quiz.QuizController
Imports WillStrohl.Modules.Quiz.QuizInfoMembers

Namespace WillStrohl.Modules.Quiz

    Partial Public MustInherit Class AnswerList
        Inherits WnsPortalModuleBase

#Region " Private Members "

        Private Const ICON_FORMAT As String = "<img src=""{0}"" alt=""{1}"" title=""{1}"" />"
        Private Const ICON_LINK_FORMAT As String = "<a href=""{0}""><img src=""{1}"" alt=""{2}"" title=""{2}"" /></a>"

        Private p_QuestionId As Integer = Null.NullInteger
        Private p_Question As QuestionInfo = Nothing
        Private p_Quiz As QuizInfo = Nothing

#End Region

#Region " Properties "

        Private ReadOnly Property QuestionId() As Integer
            Get
                If p_QuestionId = Null.NullInteger Then
                    Dim oSetting As Object = Request.Params(QUERYSTRING_QUESTION_ID_KEY)
                    If Not oSetting Is Nothing Then
                        p_QuestionId = Integer.Parse(oSetting.ToString(), Globalization.NumberStyles.Integer)
                    End If
                End If

                Return p_QuestionId
            End Get
        End Property

        Protected ReadOnly Property Question As QuestionInfo
            Get
                If p_Question Is Nothing Then
                    Dim ctlQuiz As New QuizController
                    p_Question = ctlQuiz.GetQuestion(QuestionId)
                End If

                Return p_Question
            End Get
        End Property

        Protected ReadOnly Property Quiz As QuizInfo
            Get
                If p_Quiz Is Nothing Then
                    Dim ctlQuiz As New QuizController
                    p_Quiz = ctlQuiz.GetQuiz(Question.QuizId)
                End If

                Return p_Quiz
            End Get
        End Property

#End Region

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try

                If Not Page.IsPostBack Then
                    Me.BindData()
                End If

            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try
        End Sub

        Private Sub lnkReturn_Click(sender As Object, e As System.EventArgs) Handles lnkReturn.Click
            SendToQuizView()
        End Sub

        Private Sub lnkAddAnswer_Click(sender As Object, e As System.EventArgs) Handles lnkAddAnswer.Click
            SendToEditAnswer()
        End Sub

#End Region

#Region " Private Helper Functions "

        Private Sub BindData()

            Me.LocalizeModule()

            If Not Question Is Nothing Then

                Dim sb As New StringBuilder
                sb.AppendFormat("<h2>{0}</h2>", Question.Question)
                sb.AppendFormat("<p><span class=""SubHead"">{0}:</span> {1}</p>", GetLocalizedString("lblQuestionType.Text"), LocalizeQuestionType(Question.QuestionType))
                phQuiz.Controls.Add(New LiteralControl(sb.ToString))

            End If

            Dim ctlQuiz As New QuizController
            Dim collAnswer As AnswerInfoCollection = ctlQuiz.GetAnswers(QuestionId)

            If Not collAnswer Is Nothing AndAlso collAnswer.Count > 0 Then

                rptAnswerList.DataSource = collAnswer
                rptAnswerList.DataBind()

            Else

                If QuestionId = Null.NullInteger Then
                    ' no questionid passed to the module
                    AddModuleMessage(Me, GetLocalizedString("Error.QuestionIdNull"), ModuleMessage.ModuleMessageType.RedError)
                Else
                    ' no answers available for this questionid yet
                    AddModuleMessage(Me, GetLocalizedString("Error.NoAnswers"), ModuleMessage.ModuleMessageType.YellowWarning)
                End If

            End If

        End Sub

        Private Sub LocalizeModule()

            lnkReturn.Text = GetLocalizedString("lnkReturn.Text")
            lnkAddAnswer.Text = GetLocalizedString("lnkAddAnswer.Text")

        End Sub

        Private Function LocalizeQuestionType(ByVal QuestionType As String) As String

            If String.Equals(QuestionType, "radio", StringComparison.InvariantCultureIgnoreCase) Then
                Return GetLocalizedString("QuestionType.Radio")
            Else
                Return GetLocalizedString("QuestionType.Checkbox")
            End If

        End Function

        Protected Function GetUserDisplayName(ByVal GridUserId As Object) As String

            Dim ctlUser As New Entities.Users.UserController
            Dim oUser As UserInfo = ctlUser.GetUser(PortalId, Integer.Parse(GridUserId.ToString(), Globalization.NumberStyles.Integer))

            If Not oUser Is Nothing Then
                Return oUser.DisplayName
            Else
                Return String.Format("&lt;{0}&gt;", GetLocalizedString("Error.UserNotFound"))
            End If

        End Function

        Protected Function GetDateFormat(ByVal GridDate As Object) As String

            Dim dteValue As DateTime = DateTime.Parse(GridDate.ToString())
            Return dteValue.ToString("MM/dd/yyyy hh:mm tt")

        End Function

        Protected Function GetEditIcon(ByVal GridAnswerId As Object, ByVal GridQuestionId As Object) As String

            Dim strIcon As String = Entities.Icons.IconController.IconURL("Edit", DefaultIconSize, DefaultIconStyle)
            Return String.Format(ICON_LINK_FORMAT, _
                EditUrl(String.Empty, String.Empty, "EditAnswer", String.Format("{0}={1}&{2}={3}", QUERYSTRING_ANSWER_ID_KEY, GridAnswerId, QUERYSTRING_QUESTION_ID_KEY, GridQuestionId)), _
                strIcon, _
                GetLocalizedString("Link.Edit"))

        End Function

        Protected Function GetDeleteIcon(ByVal GridQuizId As Object) As String

            Dim strIcon As String = Entities.Icons.IconController.IconURL("Delete", DefaultIconSize, DefaultIconStyle)
            Return String.Format(ICON_LINK_FORMAT, _
                EditUrl(String.Empty, String.Empty, "List", String.Format("{0}={1}&{2}={3}", QUERYSTRING_QUIZ_ID_KEY, GridQuizId.ToString(), QUERYSTRING_ACTION_KEY, "Delete")), _
                strIcon, _
                GetLocalizedString("Link.Delete"))

        End Function

        Protected Function GetBooleanFormat(ByVal GridIsCorrect As Object) As String

            If String.Equals(GridIsCorrect.ToString(), "true", StringComparison.InvariantCultureIgnoreCase) Then
                Dim strCorrectIcon As String = Entities.Icons.IconController.IconURL("Checked", DefaultIconSize, DefaultIconStyle)
                Return String.Format(ICON_FORMAT, _
                    strCorrectIcon, _
                    GetLocalizedString("Icon.Correct"))
            Else
                Dim strIncorrectIcon As String = Entities.Icons.IconController.IconURL("Unchecked", DefaultIconSize, DefaultIconStyle)
                Return String.Format(ICON_FORMAT, _
                    strIncorrectIcon, _
                    GetLocalizedString("Icon.Incorrect"))
            End If

        End Function

        Private Sub SendToQuizView()
            Response.Redirect(EditUrl(String.Empty, String.Empty, "Questions", String.Format("{0}={1}", QUERYSTRING_QUIZ_ID_KEY, Quiz.QuizId)))
        End Sub

        Private Overloads Sub SendToEditAnswer()
            SendToEditAnswer(Null.NullInteger)
        End Sub

        Private Overloads Sub SendToEditAnswer(ByVal AnswerId As Integer)

            If AnswerId > 0 Then
                Response.Redirect(EditUrl(String.Empty, String.Empty, "EditAnswer", String.Format("{0}={1}&{2}={3}", QUERYSTRING_ANSWER_ID_KEY, AnswerId, QUERYSTRING_QUESTION_ID_KEY, QuestionId)))
            Else
                Response.Redirect(EditUrl(String.Empty, String.Empty, "EditAnswer", String.Format("{0}={1}", QUERYSTRING_QUESTION_ID_KEY, QuestionId)))
            End If

        End Sub

        Private Sub HandleException(ByVal exc As Exception)
            LogException(exc)
            If Me.UserInfo.IsSuperUser Or Me.UserInfo.UserID = PortalSettings.AdministratorId Then
                AddModuleMessage(Me, _
                    String.Concat(exc.Message, "<br />", exc.StackTrace), _
                    Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            Else
                AddModuleMessage(Me, exc.Message, _
                    Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            End If
        End Sub

#End Region

    End Class

End Namespace